package cn.com.xy.sms.sdk.provider;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.ContactsDBHelper;
import cn.com.xy.sms.sdk.db.entity.ContactsColumns;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;

/**
 * @author Jinjia
 *
 *         联系人提供者
 */
public class ContactsProvider extends ContentProvider {

    private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int CONTACTS = 1;
    // private static final int CONTACT_PHONE = 2;

    public static final String AUTHORITY = "cn.com.xy.sms.sdk.provider.contacts";

    static {
        MATCHER.addURI(AUTHORITY, "contacts", CONTACTS);
        // MATCHER.addURI(AUTHORITY, "contacts/#", CONTACT_PHONE);
    }

    public static final String URI = "content://" + AUTHORITY + "/contacts";

    private static final String QUERY_CONTACT_BY_PHONE = "SELECT " + ContactsColumns.NAME + " FROM "
            + ContactsColumns.TABLE_NAME + " WHERE " + ContactsColumns.PHONE + " = ? ";

    private ContactsDBHelper mContactsDBHelper;

    @Override
    public boolean onCreate() {
        mContactsDBHelper = new ContactsDBHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        if (MATCHER.match(uri) != CONTACTS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = mContactsDBHelper.getReadableDatabase();
        Cursor cursor = db.query(ContactsColumns.TABLE_NAME, projection, selection, selectionArgs, null, null,
                sortOrder);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (MATCHER.match(uri) != CONTACTS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (values == null) {
            values = new ContentValues();
        }
        // 更新时间
        values.put(ContactsColumns.UPDATE_TIME, String.valueOf(System.currentTimeMillis()));

        String[] projection = new String[] { values.getAsString(ContactsColumns.PHONE) };

        // 判断是否存在该联系人
        SQLiteDatabase db = mContactsDBHelper.getWritableDatabase();
        Cursor queryCursor = db.rawQuery(QUERY_CONTACT_BY_PHONE, projection);
        boolean existContact = queryCursor.moveToFirst();
        queryCursor.close();

        long rowId;
        if (existContact) { // phone 存在数据库，更新数据
            rowId = db.update(ContactsColumns.TABLE_NAME, values, ContactsColumns.PHONE + " = ? ", projection);
        } else { // 该 phone 不存在数据库中，插入到数据库中
            rowId = db.insert(ContactsColumns.TABLE_NAME, null, values);
        }

        Uri resultUri = null;
        if (rowId > 0) {
            resultUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(resultUri, null);
            return resultUri;
        }
        throw new SQLException("Failed to insert row into" + uri);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        if (MATCHER.match(uri) != CONTACTS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        SQLiteDatabase db = mContactsDBHelper.getReadableDatabase();
        return db.delete(ContactsColumns.TABLE_NAME, selection, selectionArgs);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }

    /**
     * 添加联系人到数据库中
     * 
     * @param ctx 上下文
     * @param map Map object
     */
    public static void addContactsToDb(final Context ctx, final Map<String, Object> map) {
        NetUtil.executeRunnable(new Runnable() {

            @Override
            public void run() {
                try {
                    JSONObject json = DexUtil.handerContactValueMap(map);
                    if (json == null) {
                        return;
                    }

                    try {
                        JSONArray data = json.getJSONArray("data");
                        for (int i = 0; i < data.length(); ++i) {
                            JSONObject object = data.getJSONObject(i);

                            ContentValues values = new ContentValues();
                            values.put(ContactsColumns.PHONE, object.getString("phone").trim().replace("-", ""));
                            values.put(ContactsColumns.NAME, object.getString("name"));
                            values.put(ContactsColumns.DATA, object.toString());
                             /*SDK-678 hewengao 20161115 start*/
                            ContentResolver resolver =  Constant.getContext().getContentResolver();
                             /*SDK-678 hewengao 20161115 end*/
                            Uri uri = Uri.parse(ContactsProvider.URI);
                            resolver.insert(uri, values);
                        }
                    } catch (Throwable e) {
                        // e.printStackTrace();
                        LogManager.e(Constant.TAG, "addContactsToDb: ", e);

                    }

                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, e.getMessage(), e);
                }
            }
        });
    }

}
